C++ Constructors

03-11-17 Course- CPP

Constructors are the special type of member function that initialises the object automatically when it is created Compiler identifies that the given member function is a constructor by its name and return type. Constructor has same name as that of class and it does not have any return type.


..... ... .....   
class temporary
   {
       private: 
          int x;
          float y;
       public:
          temporary(): x(5), y(5.5)        /* Constructor  */
              {  
                     /* Body of constructor */
              }
          .... ...  ....
  }
  int main()
     {
        Temporary t1;
        .... ... ....
     }            

Working of Constructor

In the above pseudo code, temporary() is a constructor. When the object of class temporary is created, constructor is called and x is initialized to 5 and y is initialized to 5.5 automatically.

You can also initialise data member inside the constructor's function body as below. But, this method is not preferred.


temporary(){
   x=5;
   y=5.5;
}
/* This method is not preferred. /*

Use of Constructor in C++

Suppose you are working on 100's of objects and the default value of a data member is 0. Initialising all objects manually will be very tedious. Instead, you can define a constructor which initialises that data member to 0. Then all you have to do is define object and constructor will initialise object automatically. These types of situation arises frequently while handling array of objects. Also, if you want to execute some codes immediately after object is created, you can place that code inside the body of constructor.

Constructor Example


/*Source Code to demonstrate the working of constructor in C++ Programming */
/* This program calculates the area of a rectangle and  displays it. */ 
#include <iostream>
using namespace std;
class Area
{
    private:
       int length;
       int breadth;

    public:
       Area(): length(5), breadth(2){ }   /* Constructor */
       void GetLength()
       {
           cout<<"Enter length and breadth respectively: ";
           cin>>length>>breadth;
       }
       int AreaCalculation() {  return (length*breadth);  }
       void DisplayArea(int temp)
       {
           cout<<"Area: "<<temp;
       }
};
int main()
{
    Area A1,A2;
    int temp;
    A1.GetLength();
    temp=A1.AreaCalculation();
    A1.DisplayArea(temp);
    cout<<endl<<"Default Area when value is not taken from user"<<endl;
    temp=A2.AreaCalculation();
    A2.DisplayArea(temp);
    return 0;
}

Explanation

In this program, a class of name Area is created to calculate the area of a rectangle. There are two data members length and breadth. A constructor is defined which initialises length to 5 and breadth to 2. And, we have three additional member functions GetLength(), AreaCalculation() and DisplayArea() to get length from user, calculate the area and display the area respectively.

When, objects A1 and A2 are created then, the length and breadth of both objects are initialized to 5 and 2 respectively because of the constructor. Then the member function GetLength() is invoked which takes the value of length and breadth from user for object A1. Then, the area for the object A1 is calculated and stored in variable temp by calling AreaCalculation() function. And finally, the area of object A1 is displayed. For object A2, no data is asked from the user. So, the value of length will be 5 and breadth will be 2. Then, the area for A2 is calculated and displayed which is 10.

Output


Enter length and breadth respectively: 6
7
Area: 42
Default Area when value is not taken from user
Area: 10

Constructor Overloading

Constructor can be overloaded in similar way as function overloading. Overloaded constructors have same name(name of the class) but different number of argument passed. Depending upon the number and type of argument passed, specific constructor is called. Since, constructor are called when object is created. Argument to the constructor also should be passed while creating object. Here is the modification of above program to demonstrate the working of overloaded constructors.


/* Source Code to demonstrate the working of overloaded constructors */
#include <iostream>
using namespace std;
class Area
{
    private:
       int length;
       int breadth;

    public:
       Area(): length(5), breadth(2){ }          // Constructor without no argument
       Area(int l, int b): length(l), breadth(b){ } // Constructor with two argument
       void GetLength()
       {
           cout<<"Enter length and breadth respectively: ";
           cin>>length>>breadth;
       }
       int AreaCalculation() {  return (length*breadth);  }
       void DisplayArea(int temp)
       {
           cout<<"Area: "<<temp<<endl;
       }
};
int main()
{
    Area A1,A2(2,1);
    int temp;
    cout<<"Default Area when no argument is passed."<<endl;
    temp=A1.AreaCalculation();
    A1.DisplayArea(temp);
    cout<<"Area when (2,1) is passed as argument."<<endl;
    temp=A2.AreaCalculation();
    A2.DisplayArea(temp);
    return 0;
}

Explanation of Overloaded Constructors

For object A1, no argument is passed. Thus, the constructor with no argument is invoked which initialises length to 5 and breadth to 2. Hence, the area of object A1 will be 10. For object A2, 2 and 1 is passed as argument. Thus, the constructor with two argument is called which initialises length to l(2 in this case) and breadth to b(1 in this case.). Hence the area of object A2 will be 2.

Output


Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as argument.
Area: 2

Default Copy Constructor

A object can be initialized with another object of same type. Let us suppose the above program. If you want to initialise a object A3 so that it contains same value as A2. Then, this can be performed as:


....
int main() {
   Area A1,A2(2,1);
   Area A3(A2);     /* Copies the content of A2 to A3 */
     OR, 
   Area A3=A2;      /* Copies the content of A2 to A3 */  
}

You might think, you may need some constructor to perform this task. But, no additional constructor is needed. It is because this constructor is already built into all classes.